package com.server.thread;

import java.util.List;
import java.util.Timer;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.broad.Board_seat;
import cn.com.messageManager.MessageManager;
import cn.com.user.Poke_User;


import com.server.Board_Table;
import com.server.PokeServer;

/**
 * 线程类
 * @author jj043
 */
public class ConnectionThread 
{
	private static Logger logger = LoggerFactory.getLogger(ConnectionThread.class);
	private Board_seat seat;                                //坐位
	private Poke_User user;	                                //线程下面的用户
	private IoSession session;                              //会话
	private Timer timer = null;                             //时间
	private boolean isout = false;                          //是否退出
	private ThreadTask task = null;                         //断线定时等待任务
	private Board_Table table = null;                       //桌子
	boolean on_off = true;                                  //调试开关
	private boolean answer_flag = false;                    //询问标志
	

	
	/**
	 * 处理前台信息
	 * 绑定信息
	 * @param array
	 */
	public void beging(byte[] array)
	{
		try
		{
			//处理接到的用户的信息.如果计算得到只有一个用户了，那么直接结束游戏，重新启动游戏
			Board_Table.mg.parseReceiveMessage( array, this.session, this);
		}
		catch(Exception e)
		{	
			String str = "";
			 e.printStackTrace();
			if(array == null)
			{
				str = "array  为空";
			}else if(this.session == null)
			{
				str = "this.session  为空";
			}else
			{
				str = "不知道是什么为空";
			}
			logger.error("   beging  throw error:{}", str);
		}
	}
	
	/**
	 * 启动一个2分钟定时的任务，启动定时器
	 */
	public void waitReConnection()
	{
		this.isout = false;
		this.getTable().addOffLineList(this);
		//this.timer.schedule(task, 1000*60*3);
		
		//this.isout=true;
		//this.dispose();
		
	}
	
	/**
	 * 取得当前用户登陆的远程IP和端口信息.
	 * @param session
	 * @return
	 */
	public String getSessionInfo()
	{
		String info = session.getRemoteAddress().toString();
		return info;
	}

	
	
	/**
	 * 用户掉线2分种未进来
	 * 消毁此线程
	 */
	public synchronized void dispose()
	{
		int i=0;
		int userid = 0;
		boolean if_zhang=false;
		boolean if_seat=false;
		try
		{
			Board_seat seat = null;
			Poke_User user = null;
				
			if( (user = this.getUser()) != null )
			{
				this.getTable().getMessageManager().cast_userout(user.getUser_id(), this.getTable());  //  广播用户离开
				userid=this.getUser().getUser_id();
				//清除桌子上相关
				if( this.getTable() != null )
				{
					
					//找到这个座位，清空座位下面的信息
					if(( seat = this.getSeat()) != null )
					{
						if_seat=true;
						seat.resetSeat();//重置座位
						if_zhang=seat.isIf_zhan();
						if(this.getTable().getActive_list().contains(seat))
						{
							this.getTable().getActive_list().remove(seat);
						}
					}else
					{
						for(byte j=0;j<this.getTable().getLooklist().size();j++)
						{
							if(userid==this.getTable().getLooklist().get(j).getUser_id())
							{
								this.getTable().getLooklist().remove(j);
							}
						}
					}
					
					try
					{
						this.getTable().getThreadpool().remove(this);					
					}catch(Exception e)
					{
						e.printStackTrace();
						logger.error("ConnectionThread 中移除桌子链接线程有错：{}"+e.getMessage());
					}
					
					for(int j = 0;j<this.getTable().getThreadpool().size();j++)
					{
						try
						{
							if(this.getTable().getThreadpool().get(j).getUser() != null)
							{
								logger.info("有用户，删除用户");
								if(!PokeServer.usermap.containsKey(String.valueOf(this.getTable().getThreadpool().get(j).getUser().getUser_id())))
								{
									ConnectionThread th = this.getTable().getThreadpool().get(j);
									th.setUser(null);
									th.setTable(null);
									System.out.println("检测移除失效线程是否成功："+this.getTable().getThreadpool().remove(j));
									th.dispose();
								}
							}else
							{
								ConnectionThread th = this.getTable().getThreadpool().get(j);
								th.setTable(null);
								System.out.println("检测移除失效线程是否成功22222："+this.getTable().getThreadpool().remove(j));
							}
						}catch(Exception e)
						{
							logger.error("移除失效线程的方法出错：{}",e.getMessage());
						}
					}
					System.out.println( "。。。。。当 前在线用户："+this.getTable().getThreadpool().size());
					if( this.getTable().getThreadpool().size() < 1 )
					{
						//if(this.getTable().getIsClock() == 1)
						//{
						//	this.getTable().setPassword("");
						//	this.getTable().setIsClock((byte) 0);
						//}
						try
						{
							this.getTable().removeDemoListener(this.getTable().getListener());
							PokeServer.tablemap.remove(this.getTable().getTableId());
							logger.info("删除"+this.getTable().getTableId()+"桌子的侦听器！！！");
							System.gc();
						}catch(Exception e)
						{
							e.printStackTrace();
							logger.error("删除桌子的侦听和从map里面移除侦听出错：{}", e.getMessage());
						}
					}
				}
				//用户的钱返回给座位信息，找到对应的座位，广播清空座位信息
				try
				{
					//删除关联列表里面的值
					i = MessageManager.usermanager.userOut(user.getUser_id(),this.getTable().getId(),if_seat);
					logger.info("删除关连信息："+i);
				}catch(Exception e)
				{
					e.printStackTrace();
					logger.error("删除关连信息出错：{}", e.getMessage());
				}
				//value = user.getM_count();
				//if(value > 0)
				//{
				//		try
				//		{
				//			MessageManager.usermanager.addCharm_value(value, user.getUser_id());
				//		}catch(Exception e)
				//		{
				//			e.printStackTrace();
				//			logger.error("增加经验出错：{}", e.getMessage());
					//	}
				//}
				
				
				user.setM_count(0);
				logger.info("．．．{}用户离开．．．",String.valueOf(user.getUser_id())+"/"+user.getUser_name());
				try
				{
					System.out.println("  POKESERVER    删除用户是否成功：    "+ PokeServer.usermap.remove(String.valueOf(user.getUser_id())));
					// 从服务器上删除这个用户PokeServer.usermap.remove(user.getUser_id()); // 从服务器上删除这个用户
				}catch(Exception e)
				{
					e.printStackTrace();
					logger.error("ConnectionThread 中释放服务器中用户有错：{}",e.getMessage());
				}
				if(PokeServer.threadmap.containsKey(user.getUser_id()))
				{//从掉线线程中移除这个线程
					//如果有关联，那么就删除这个关联
					PokeServer.threadmap.remove(user.getUser_id());
				}
			}
			else
			{
				logger.info("没有用户");
				reset();
				return;
			}
			reset();
			
			logger.info("内存中有多少用户："+PokeServer.usermap.size());
			logger.info("内存中有多少桌子："+PokeServer.tablemap.size());
			logger.info("内存中有多少等待线程："+PokeServer.threadmap.size());
			
			System.out.println("。。。。。。。。。释放之后threadmap的长度。。。。。。。"+PokeServer.threadmap.size());
		}catch(Exception e)
		{
			e.printStackTrace();
			logger.error("释放拥护出错：{}", e.getMessage());
		}
	}
	
	
    public void reset()
    {
    	if(this.getSession()!= null)
		{
			if(this.getSession().containsAttribute("thread"))
			{
				this.getSession().removeAttribute("thread");
			}
			if(this.getSession().containsAttribute("ownseat"))
			{
				this.getSession().removeAttribute("ownseat");
			}
			//Board_Table.mg.gotoTingSuss(this.getSession());  //告诉自己离开成功
		}
		
		if(this.getTask()!=null)
		{
			this.getTask().conn = null;
		}
		else
		{
			return;
		}
		
		this.setSeat(null);
		this.setTable(null);
		this.setTask(null);
		this.setTimer(null);
		this.setUser(null);
		this.setSession(null);
		this.seat=null;
    }
	public boolean isAnswer_flag() 
	{
		return answer_flag;
	}
	public void setAnswer_flag(boolean answer_flag) 
	{
		this.answer_flag = answer_flag;
	}
	public Board_Table getTable() 
	{
		return table;
	}
	public void setTable(Board_Table table) 
	{
		this.table = table;
	}
	public ConnectionThread(IoSession session)
	{
		this.session = session;
	}
	/**
	 * 登陆用户
	 * @return
	 */
	public Poke_User getUser() 
	{
		return user;
	}

	/**
	 * 登陆用户
	 * @return
	 */
	public void setUser(Poke_User user) 
	{
		this.user = user;
	}

	/**
	 * 会话
	 * @return
	 */
	public IoSession getSession() 
	{
		return session;
	}
	
	/**
	 * 会话
	 * @return
	 */
	public void setSession(IoSession iosession)
	{
		session = iosession;
	}

	/**
	 * 坐位
	 * @return
	 */
	public Board_seat getSeat() 
	{
		return seat;
	}

	/**
	 * 坐位
	 * @return
	 */
	public void setSeat(Board_seat seat)
	{
		this.seat = seat;
	}

	/**
	 * 时钟
	 * @return
	 */
	public Timer getTimer() 
	{
		return timer;
	}

	/**
	 * 时钟
	 * @return
	 */
	public void setTimer(Timer timer) 
	{
		this.timer = timer;
	}

	/**
	 * 是否退出
	 */
	public boolean isIsout() 
	{
		return isout;
	}

	/**
	 * 是否退出
	 */
	public void setIsout(boolean isout) 
	{
		this.isout = isout;
	}

	/**
	 * 任务
	 * @return
	 */
	public ThreadTask getTask() 
	{
		return task;
	}

	/**
	 * 任务
	 * @return
	 */
	public void setTask(ThreadTask task) 
	{
		this.task = task;
	}
}
